<?php

/**
*/

define('IN_ECS', true);

require('./init.php');
require_once('../includes/cls_json.php');

$nearID = $_REQUEST['nearID'];
if (is_blank($nearID)) {
	exit(0);
}

$userType = (is_blank($_REQUEST['userType']) ? 0 : $_REQUEST['userType']);
$userName = (is_blank($_REQUEST['userName']) ? 'anonymous' : urlencode(serialize(json_str_iconv($_REQUEST['userName']))));

$json = new JSON;

$res = array('error' => 0);

if ($userType == 0) {
	$sql = " SELECT 1 FROM " . $ecs->table('vcustomer_login') . " WHERE token_id = '" . $nearID . "'";
	if ($db->getOne($sql)) {
		$sql = " UPDATE " .  $ecs->table('vcustomer_login') . " SET last_time = " . time() .
			" WHERE token_id = '" . $nearID . "'";
	} else {
		$sql = " INSERT INTO " . $ecs->table('vcustomer_login') . " (token_id, user_name, region_id, last_time) " .
			" VALUES ('$nearID', '$userName', '$_REQUEST[region]', " . time() . ")";
	}
	$db->query($sql);
} else {
	$sql = " SELECT 1 FROM " . $ecs->table('vsalesperson_login') . " WHERE token_id = '" . $nearID . "'";
	if ($db->getOne($sql)) {
		$sql = " UPDATE " .  $ecs->table('vsalesperson_login') . " SET last_time = " . time() .
			" WHERE token_id = '" . $nearID . "'";
	} else {
		$sql = " INSERT INTO " . $ecs->table('vsalesperson_login') . " (token_id, user_name, last_time) " .
			" VALUES ('$nearID', '$userName', " . time() . ")";
	}
	$db->query($sql);
}

$sql = " DELETE FROM " . $ecs->table('vcustomer_login') . " WHERE " . time() . " - last_time > 120 ";
$db->query($sql);
$sql = " DELETE FROM " . $ecs->table('vsalesperson_login') . " WHERE " . time() . " - last_time > 120 ";
$db->query($sql);
$sql = " UPDATE " . $ecs->table('vsalesperson_login') .
	" SET customer_id = NULL, customer_token = NULL " .
	" WHERE customer_id is NOT NULL AND customer_id not in ( " .
	"     SELECT id " .
	"       FROM " . $ecs->table('vcustomer_login') .
	" )";
$db->query($sql);
$sql = " DELETE FROM " . $ecs->table('vwaiting_queue') . 
	" WHERE customer_id not in ( " .
	"     SELECT id " .
	"       FROM " . $ecs->table('vcustomer_login') .
	" )";
$db->query($sql);
$sql = " DELETE FROM " . $ecs->table('vwaiting_queue') . 
	" WHERE salesperson_id not in ( " .
	"     SELECT id " .
	"       FROM " . $ecs->table('vsalesperson_login') .
	" )";
$db->query($sql);

$val = $json->encode($res);

die($val);

function is_blank($value) {
	return empty($value) && !is_numeric($value);
}
?>